#include <iostream>
#include <fstream>
#include "SortingConfig.h"

using namespace std;

void swap(auto &a, auto &b) {
    auto t=a;
    a = b;
    b = t;
}

void merge_sort(int *arr, int n) {
    // 归并排序算法
    int arr_[n];
    int *arr_cr=arr, *arr_cp=arr_;
    int step=1;
    while (step < n) {
        // cout << "step:"<<step<<endl;
        for(int i=0; i<n; i+=2*step) {
            // 确定本轮归并排序的两个子数组的开始和结束下标
            int l=i, r=i+step;
            int le=min(n, i+step), re=min(n, i+2*step);
            int j=i;
            // cout << l << ',' << le << "  " << r << ","<<re<<endl;
            while(l <le || r < re) {
                if (l < le && r < re) {
                    if (arr_cr[l] <= arr_cr[r]) {
                        arr_cp[j] = arr_cr[l];
                        l ++;
                    } else {
                        arr_cp[j] = arr_cr[r];
                        r ++;
                    }
                } else if (l < le) {
                    arr_cp[j] = arr_cr[l];
                    l ++;
                } else {
                    arr_cp[j] = arr_cr[r];
                    r ++;
                }
                j ++;
            }
        }
        // 扩大步长
        step *=2;
        // 交换目标数组和原数组
        swap(arr_cr, arr_cp);
    }
    if (arr_cr != arr) {
        for(int i=0; i<n; ++i) arr[i] = arr_cr[i];
    }
}

int main(int argc, char *argv[]) {
    cout << "Sorting Version: " << Sorting_VERSION_MAJOR 
         << "." << Sorting_VERSION_MINOR<<endl;
    // 参数解析
    ifstream input;
    if (argc > 1) {
        input.open(argv[1], ios::in);
    }

    int n;
    if (argc > 1) input >> n;
    else cin >> n;
    int arr[n];
    if (argc > 1){
        for(int i=0; i<n;++i) input >> arr[i];
        input.close();
    } else {
        for(int i=0; i<n;++i) cin >> arr[i];
    }
    // 排序
    merge_sort(arr, n);

    for(int i=0; i<n; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}